import { defineStore } from 'pinia';
import { publicRoutes, router } from '../router/index';
import { useUsersStore } from './user';
import { Menu } from '../bean/Menu';
import { RouteRecordRaw } from "vue-router";

interface IRouteState {
  /** 是否初始化权限路由的生成 */
  isInitRoute: boolean;
  /** 菜单渲染数据 */
  menus: Menu[];
}

export const useRouteStore = defineStore('route', {
  state: (): IRouteState => ({
    isInitRoute: false,
    menus: []
  }),
  getters: {},
  actions: {
    /** 初始化权限路由 */
    initRoute() {
      const userStore = useUsersStore();
      // 根据权限过滤后的路由
      var allowedRoute = filterRouteByPermissionUrl(publicRoutes, userStore.permissionUrl);
      // 添加路由
      allowedRoute.forEach((allowedRoute) => {
        if (allowedRoute.children?.length) {
          router.addRoute(allowedRoute);
        } 
      });
      const menus = getMenuList(allowedRoute);
      this.setMenus(menus);
      this.isInitRoute = true;
    },
    /** 设置菜单 */
    setMenus(menus: Menu[]) {
      this.menus = menus;
    }
  }
});

// 根据权限过滤路由
function filterRouteByPermissionUrl(routes: RouteRecordRaw[], permissionUrl: any) {
  var res: RouteRecordRaw[] = [];
  routes.forEach((route: RouteRecordRaw) => {
    // 需要重新生成一个tmp对象，否则routes对象会被改变
    const tmp = {...route}
    if (permissionUrl.includes(tmp.path)) {
      res.push(tmp);
    } else {
      if (tmp.children && tmp.children.length > 0) {
        tmp.children = filterRouteByPermissionUrl(tmp.children, permissionUrl)
        res.push(tmp);
      }
    }
  });
  return res;
}

function getMenuList(routes: RouteRecordRaw[]) {
  const menus: Menu[] = [];
  routes.forEach((route: RouteRecordRaw) => {
    const menuItem: Menu = {
      path: route.path,
      title: route.meta?.title || '',
      icon: route.meta?.icon,
      sort: route.meta?.sort
    };
    if (route.children && route.children.length > 0) {
      menuItem.children = getMenuList(route.children);
    }
    menus.push(menuItem);
  });
  menus.sort((a, b) => (a.sort && b.sort) ? a.sort - b.sort : 1);
  return menus;
}